package org.supper.auth.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
import org.supper.auth.exception.AuthExceptionEntryPoint;
import org.supper.auth.exception.MyExtendAccessDeniedHandler;

import javax.annotation.Resource;

/**
 * @author huqi
 */
@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class ResourceServiceAdapter extends ResourceServerConfigurerAdapter {
    public static final String RESOURCE_ID = "res1";

    @Resource
    private RedisConnectionFactory redisConnectionFactory;

    @Resource
    private AuthExceptionEntryPoint authExceptionEntryPoint;

    @Resource
    MyExtendAccessDeniedHandler extendAccessDeniedHandler;

    public RedisTokenStore tokenStore() {
        return new RedisTokenStore(redisConnectionFactory);
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.resourceId(RESOURCE_ID)
                .tokenStore(tokenStore())
                .stateless(true);
        resources.accessDeniedHandler(extendAccessDeniedHandler);
        resources.authenticationEntryPoint(authExceptionEntryPoint);
    }


    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable()
                .authorizeRequests()
                .antMatchers("/auth/login",
                        "/auth/phoneLogin",
                        "/swagger**/**",
                        "/v2/api-docs",
                        "/static/**",
                        "/webjars/**",
                        "/imgs/**",
                        "/actuator/health",
                        "/video/selectAll",
                        "/user/getUserName").permitAll()
                .antMatchers("/user/login").hasAnyAuthority("ADMIN1")
                .antMatchers("/**")//匹配/**的请求，都受资源服务器的保护
                .authenticated();
    }

}
